<template>
  <div class="company-attendance-container">
    <!-- 新增下拉框选择月份 -->
    <div class="select-month">
      <label>当前月份：</label>
      <el-select v-model="selectedMonth" placeholder="选择月份" @change="fetchDataByMonth">
        <el-option
          v-for="month in availableMonths"
          :key="month"
          :label="month"
          :value="month"
        >
        </el-option>
      </el-select>
    </div>
    <!-- 显示公司名称 -->
    <h1 class="company-name">宇宙科技有限责任公司</h1>
    <!-- 各部门核心指标卡片 -->
    <div class="overview-cards">
      <div class="card" v-for="(dept, index) in deptOverviewData" :key="`overview-${dept.deptId}`" :class="'card-bg-' + (index % 4)">
        <h3>{{ dept.deptName }}</h3>
        <p>部门总人数: {{ dept.deptUser }}</p>
        <p>部门本月准时签到次数: {{ dept.normalAttendanceDays }}</p>
        <p>部门本月迟到次数: {{ dept.lateCount }}</p>
        <!-- 这里原先是旷工次数，现在保持为迟到次数 -->
        <p>部门本月迟到次数: {{ dept.lateCount }}</p>
        <!-- 新增部门本月请假人数 -->
        <p>部门本月请假人数: {{ dept.approvedLeaveCount }}</p>
      </div>
    </div>

    <!-- 各部门当日出勤率柱状图 -->
    <div class="trend-charts">
      <h2>各部门当日出勤率</h2>
      <div id="dailyAttendanceRateBarChart"></div>
    </div>

    <!-- 部门排名表格（本月迟到次数TOP5） -->
    <div class="ranking-section">
      <h2>部门本月考勤排名（迟到次数TOP5）</h2>
      <table class="department-table">
        <thead>
        <tr>
          <th>部门名称</th>
          <th>迟到次数</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index) in deptRanking" :key="`ranking-${item.deptId}`">
          <td>{{ item.deptName }}</td>
          <td>{{ item.lateCount }}</td>
        </tr>
        </tbody>
      </table>
    </div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getSignStatistic } from "@/api/attendance/signRecord";
import { listDept } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { listLeaveRecord } from "@/api/leave/leaveTeacherRecord";

export default {
  data() {
    return {
      loading: true,
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      queryUser: {
        pageNum: 1,
        pageSize: 100000,
        deptId: undefined
      },
      userList: [],
      deptList: [],
      allAttendanceData: [],
      deptOverviewData: [],
      deptRanking: [],
      dailyAttendanceRateBarChart: null,
      leaveRecordList: [], // 新增存储请假记录
      availableMonths: [],
      selectedMonth: ''
    };
  },
  mounted() {
    this.fetchAllData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    async fetchAllData() {
      try {
        this.loading = true;
        const deptResponse = await listDept(this.queryParams);
        this.deptList = deptResponse.data.slice(1);
        const attendanceResponse = await getSignStatistic(this.queryParams);
        this.allAttendanceData = attendanceResponse.data || [];
        const userListResponse = await listUser(this.queryUser);
        this.userList = userListResponse.rows || [];
        // 获取请假记录
        const leaveResponse = await listLeaveRecord(this.queryParams);
        this.leaveRecordList = leaveResponse.rows;

        this.extractAvailableMonths();
        this.selectedMonth = this.getCurrentMonth();

        this.fetchDataByMonth();
      } catch (error) {
        console.error('数据加载失败，详细错误信息:', error);
        if (error.response) {
          console.error('响应状态码:', error.response.status);
          console.error('响应数据:', error.response.data);
        }
        this.$message.error('加载公司考勤数据失败');
      }
    },

    extractAvailableMonths() {
      const months = new Set();
      this.allAttendanceData.forEach(item => {
        const date = new Date(item.signTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        months.add(`${year}-${month}`);
      });
      this.leaveRecordList.forEach(item => {
        const date = new Date(item.startTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        months.add(`${year}-${month}`);
      });
      this.availableMonths = Array.from(months).sort();
    },

    getCurrentMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },

    async fetchDataByMonth() {
      const [year, month] = this.selectedMonth.split('-');
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0);

      const attendanceResponse = await getSignStatistic(this.queryParams);
      this.allAttendanceData = attendanceResponse.data || [];
      const leaveResponse = await listLeaveRecord(this.queryParams);
      this.leaveRecordList = leaveResponse.rows;

      const filteredAttendanceData = this.allAttendanceData.filter(item => {
        const signDate = new Date(item.signTime.split(' ')[0]);
        return signDate >= startDate && signDate <= endDate;
      });

      const filteredLeaveRecordList = this.leaveRecordList.filter(item => {
        const leaveDate = new Date(item.startTime);
        return leaveDate >= startDate && leaveDate <= endDate;
      });

      this.deptOverviewData = [];
      this.deptList.forEach(dept => {
        const deptData = filteredAttendanceData.filter(item => item.deptId === dept.deptId);
        const overview = this.calculateOverview(deptData, dept.deptId, filteredLeaveRecordList);
        this.deptOverviewData.push({...dept, ...overview});
      });

      this.generateDeptRanking(filteredAttendanceData);
      this.calculateDailyAttendanceRate(filteredAttendanceData);

      // 使用 $nextTick 和 requestAnimationFrame 确保 DOM 更新后再初始化 ECharts
      this.$nextTick(() => {
        requestAnimationFrame(() => {
          this.initDailyAttendanceRateBarChart();
          this.loading = false;
        });
      });
    },

    calculateOverview(monthlyDeptData, deptId, filteredLeaveRecordList) {
      // 根据deptId从this.userList中筛选出该部门的用户
      const deptUsers = this.userList.filter(user => user.deptId === deptId);
      const deptUser = deptUsers.length;

      let normalAttendanceDays = 0;
      let lateCount = 0;
      let absenteeismCount = 0;

      monthlyDeptData.forEach(item => {
        if (item.signStatus === 1) {
          normalAttendanceDays++;
        } else if (item.signStatus === 2) {
          lateCount++;
        } else if (item.signStatus === 3) {
          absenteeismCount++;
        }
      });

      // 统计该部门审批通过的请假人数
      const approvedLeaveRecords = filteredLeaveRecordList.filter(record =>
        record.deptId === deptId && record.approvalStatus === 1
      );
      const approvedLeaveCount = new Set(approvedLeaveRecords.map(record => record.userId)).size;

      return {
        deptUser,
        normalAttendanceDays,
        lateCount,
        absenteeismCount,
        approvedLeaveCount // 新增请假人数信息
      };
    },

    generateDeptRanking(filteredAttendanceData) {
      const deptStats = {};
      filteredAttendanceData.forEach(item => {
        if (!deptStats[item.deptId]) {
          deptStats[item.deptId] = {deptId: item.deptId, deptName: item.deptName, lateCount: 0};
        }
        if (item.signStatus === 2) deptStats[item.deptId].lateCount++;
      });

      this.deptRanking = Object.values(deptStats)
        .sort((a, b) => b.lateCount - a.lateCount)
        .slice(0, 5);
    },

    calculateDailyAttendanceRate(filteredAttendanceData) {
      this.deptList.forEach(dept => {
        // 根据deptId从this.userList中筛选出该部门的用户
        const deptUsers = this.userList.filter(user => user.deptId === dept.deptId);
        const deptUser = deptUsers.length;
        const currentDate = new Date();
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth() + 1;
        const currentDay = currentDate.getDate();
        const startOfDay = new Date(currentYear, currentMonth - 1, currentDay);
        const endOfDay = new Date(currentYear, currentMonth - 1, currentDay + 1);
        const deptData = filteredAttendanceData.filter(item => item.deptId === dept.deptId);
        const dailyAttendanceData = deptData.filter(item => {
          const signDate = new Date(item.signTime.split(' ')[0]);
          return signDate >= startOfDay && signDate < endOfDay;
        });
        // 统计signStatus为0和2的人数 准时和迟到
        // const validAttendanceCount = dailyAttendanceData.filter(item => [0, 2].includes(item.signStatus)).length;
        // 按用户ID去重
        const validAttendanceRecords = dailyAttendanceData.filter(item => [0, 1].includes(item.signStatus));
        const validUserIds = new Set(validAttendanceRecords.map(record => record.userId));
        const validAttendanceCount = validUserIds.size;
        // 避免除零错误
        const dailyAttendanceRate = deptUser > 0 ? (validAttendanceCount / deptUser) * 100 : 0;
        dept.dailyAttendanceRate = dailyAttendanceRate.toFixed(2);
        dept.dailyAttendanceCount = validAttendanceCount;
      });
    },

    initDailyAttendanceRateBarChart() {
      const deptNames = this.deptList.map(dept => dept.deptName);
      const dailyAttendanceRates = this.deptList.map(dept => parseFloat(dept.dailyAttendanceRate));
      const dailyAttendanceCounts = this.deptList.map(dept => dept.dailyAttendanceCount);
      const deptUserCounts = this.deptList.map(dept => {
        const deptUsers = this.userList.filter(user => user.deptId === dept.deptId);
        return deptUsers.length;
      });

      // 检查是否有数据
      if (deptNames.length === 0 || dailyAttendanceRates.length === 0) {
        console.error('没有可用的出勤数据来绘制柱状图');
        return;
      }

      this.dailyAttendanceRateBarChart = echarts.init(document.getElementById('dailyAttendanceRateBarChart'));
      this.dailyAttendanceRateBarChart.setOption({
        title: {
          text: '各部门当日出勤率'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            const index = params[0].dataIndex;
            return `${deptNames[index]}<br/>打卡人数: ${dailyAttendanceCounts[index]}<br/>总人数: ${deptUserCounts[index]}<br/>出勤率: ${dailyAttendanceRates[index]}%`;
          }
        },
        xAxis: {
          type: 'category',
          data: deptNames
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          data: dailyAttendanceRates,
          type: 'bar',
          itemStyle: {
            color: '#3b82f6'
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }]
      });
    },

    handleResize() {
      if (this.dailyAttendanceRateBarChart) {
        this.dailyAttendanceRateBarChart.resize();
      }
    }
  }
};
</script>

<style scoped>
/* 整体容器样式 */
.company-attendance-container {
  padding: 32px;
  background-color: #f9fafb;
  border-radius: 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
  position: relative;
}

.select-month {
  margin-bottom: 20px;
}

/* 公司名称样式 */
.company-name {
  font-size: 32px;
  font-weight: 700;
  color: #374151;
  margin-bottom: 32px;
  text-align: center;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 各部门核心指标卡片样式 */
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 32px;
  margin-bottom: 48px;
}

.card {
  padding: 32px;
  border-radius: 16px;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  background-color: #fff;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-bg-0 {
  background-color: #e5f6ff;
  border-top: 4px solid #3b82f6;
}

.card-bg-1 {
  background-color: #fff6cc;
  border-top: 4px solid #f59e0b;
}

.card-bg-2 {
  background-color: #ffe5e5;
  border-top: 4px solid #ef4444;
}

.card-bg-3 {
  background-color: #e5ffe5;
  border-top: 4px solid #22c55e;
}

.card h3 {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
}

.card p {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 8px;
}

/* 各部门当日出勤率柱状图样式 */
.trend-charts {
  margin-bottom: 48px;
}

.trend-charts h2 {
  font-size: 24px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 24px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

#dailyAttendanceRateBarChart {
  height: 500px;
  border-radius: 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
  background-color: #fff;
  padding: 24px;
}

/* 部门排名表格样式 */
.ranking-section {
  margin-top: 48px;
}

.ranking-section h2 {
  font-size: 24px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 24px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.department-table {
  width: 100%;
  border-collapse: collapse;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
  border-radius: 16px;
  overflow: hidden;
  background-color: #fff;
}

.department-table th,
.department-table td {
  padding: 20px 24px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.department-table th {
  background-color: #f3f4f6;
  font-weight: 600;
  color: #374151;
}

.department-table tr:hover {
  background-color: #f9fafb;
}

/* 加载状态样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.loading-spinner {
  border: 6px solid rgba(0, 0, 0, 0.1);
  border-left-color: #374151;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
